<template>
  <div v-if="visible" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50" @click="$emit('close')">
    <div class="bg-white rounded-lg shadow-xl max-w-6xl w-full mx-4 max-h-[90vh] overflow-hidden" @click.stop>
      <!-- 模态框头部 -->
      <div class="flex items-center justify-between p-4 bg-gradient-to-r from-blue-600 via-purple-600 to-blue-700 shadow-lg">
        <h2 class="text-xl font-semibold text-white">
          {{ isEdit ? '编辑章节配置' : '新增章节配置' }}
        </h2>
        <button @click="$emit('close')" class="text-white hover:text-blue-200 transition-colors p-1 rounded-full hover:bg-white hover:bg-opacity-20">
          <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
          </svg>
        </button>
      </div>

      <!-- 模态框内容 -->
      <div class="p-3 overflow-y-auto max-h-[calc(90vh-120px)]">
        <form @submit.prevent="handleSubmit">
          <!-- 基本信息 -->
          <div class="mb-8">
            <h3 class="text-lg font-medium text-gray-900 mb-4">基本信息</h3>
            <div class="flex gap-6">
              <div class="w-[10%]">
                <label class="block text-sm font-medium text-gray-700 mb-2">章节号</label>
                <input
                  v-model.number="formData.chapterNumber"
                  type="number"
                  :min="isEdit ? 1 : minChapterNumber"
                  required
                  :disabled="isEdit"
                  @keydown="preventKeyboardInput"
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100"
                  placeholder="请输入章节号"
                >
              </div>
              <div class="w-[90%]">
                <label class="block text-sm font-medium text-gray-700 mb-2">章节标题</label>
                <input
                  v-model="formData.title"
                  type="text"
                  required
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  placeholder="请输入章节标题"
                >
              </div>
            </div>
            <div class="mt-6">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">章节描述</label>
                <textarea
                  v-model="formData.description"
                  rows="3"
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  placeholder="请输入章节描述"
                ></textarea>
              </div>
              <div>
                <label class="flex items-center">
                  <input
                    v-model="formData.isEnabled"
                    type="checkbox"
                    class="rounded border-gray-300 text-blue-600 shadow-sm focus:border-blue-300 focus:ring focus:ring-blue-200 focus:ring-opacity-50"
                  >
                  <span class="ml-2 text-sm text-gray-700">启用此章节</span>
                </label>
              </div>
            </div>
          </div>

          <!-- 学习材料配置 -->
          <div class="mb-8">
            <div class="flex items-center justify-between mb-4">
              <h3 class="text-lg font-medium text-gray-900">学习材料配置</h3>
              <div class="text-sm text-gray-500">
                总权重: {{ totalWeight }}%
                <span v-if="totalWeight !== 100" class="text-red-500 ml-2">
                  (建议总权重为100%)
                </span>
              </div>
            </div>
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
              <!-- 讲义配置 -->
              <MaterialConfig
                v-model="formData.lectureConfig"
                title="讲义"
                icon="📖"
                color="blue"
                :chapter-number="formData.chapterNumber"
                material-type="docx"
                @update:modelValue="handleLectureConfigUpdate"
              />
              
              <!-- 课件配置 -->
              <MaterialConfig
                v-model="formData.slidesConfig"
                title="课件"
                icon="📊"
                color="green"
                :chapter-number="formData.chapterNumber"
                material-type="pptx"
                @update:modelValue="handleSlidesConfigUpdate"
              />
              
              <!-- 视频配置 -->
              <MaterialConfig
                v-model="formData.videoConfig"
                title="视频"
                icon="🎥"
                color="purple"
                :chapter-number="formData.chapterNumber"
                @update:modelValue="handleVideoConfigUpdate"
              />
              
              <!-- 示例材料配置 -->
              <MaterialConfig
                v-model="formData.exampleConfig"
                title="示例材料"
                icon="💻"
                color="yellow"
                :chapter-number="formData.chapterNumber"
                @update:modelValue="handleExampleConfigUpdate"
              />
              
              <!-- 实践课堂练习配置 -->
              <MaterialConfig
                v-model="formData.practiceConfig"
                title="实践课堂练习"
                icon="🔧"
                color="indigo"
                :chapter-number="formData.chapterNumber"
                @update:modelValue="handlePracticeConfigUpdate"
              />
              
              <!-- 作业配置 -->
              <MaterialConfig
                v-model="formData.assignmentConfig"
                title="作业"
                icon="📝"
                color="red"
                :chapter-number="formData.chapterNumber"
                @update:modelValue="handleAssignmentConfigUpdate"
              />
            </div>
          </div>

          <!-- 权重配置 -->
          <div class="mb-8">
            <h3 class="text-lg font-medium text-gray-900 mb-4">权重配置</h3>
            <div class="bg-gray-50 p-4 rounded-lg">
              <div class="grid grid-cols-2 md:grid-cols-3 gap-4">
                <div v-if="formData.lectureConfig">
                  <label class="block text-sm font-medium text-gray-700 mb-1">讲义权重</label>
                  <input
                    v-model.number="formData.weightConfig.lecture"
                    type="number"
                    min="0"
                    max="100"
                    class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                </div>
                <div v-if="formData.slidesConfig">
                  <label class="block text-sm font-medium text-gray-700 mb-1">课件权重</label>
                  <input
                    v-model.number="formData.weightConfig.slides"
                    type="number"
                    min="0"
                    max="100"
                    class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                </div>
                <div v-if="formData.videoConfig">
                  <label class="block text-sm font-medium text-gray-700 mb-1">视频权重</label>
                  <input
                    v-model.number="formData.weightConfig.video"
                    type="number"
                    min="0"
                    max="100"
                    class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                </div>
                <div v-if="formData.exampleConfig">
                  <label class="block text-sm font-medium text-gray-700 mb-1">示例权重</label>
                  <input
                    v-model.number="formData.weightConfig.example"
                    type="number"
                    min="0"
                    max="100"
                    class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                </div>
                <div v-if="formData.practiceConfig">
                  <label class="block text-sm font-medium text-gray-700 mb-1">实践权重</label>
                  <input
                    v-model.number="formData.weightConfig.practice"
                    type="number"
                    min="0"
                    max="100"
                    class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                </div>
                <div v-if="formData.assignmentConfig">
                  <label class="block text-sm font-medium text-gray-700 mb-1">作业权重</label>
                  <input
                    v-model.number="formData.weightConfig.assignment"
                    type="number"
                    min="0"
                    max="100"
                    class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                </div>
              </div>
              <div class="mt-4 text-sm text-gray-600">
                <p>总权重: {{ totalWeight }}%</p>
                <p v-if="totalWeight !== 100" class="text-orange-600">建议总权重为100%</p>
              </div>
            </div>
          </div>

          <!-- 错误信息 -->
          <div v-if="error" class="mb-4 p-3 bg-red-100 border border-red-400 text-red-700 rounded">
            {{ error }}
          </div>

          <!-- 操作按钮 -->
          <div class="flex justify-end space-x-3 pt-6 border-t">
            <button
              type="button"
              @click="closeModal"
              class="px-4 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
            >
              取消
            </button>
            <button
              type="submit"
              :disabled="loading"
              class="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50"
            >
              <span v-if="loading">保存中...</span>
              <span v-else>{{ isEdit ? '更新' : '创建' }}</span>
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { useAuthStore } from '@/stores/auth'
import MaterialConfig from './MaterialConfig.vue'

interface UrlItem {
  url: string
  title: string
}

interface UploadedFile {
  filename: string
  originalName: string
  size: number
  url: string
  path: string
}

interface MaterialConfigType {
  urls?: UrlItem[]
  weight: number
  isRequired?: boolean
  allowDownload?: boolean
  duration?: number
  deadline?: string
  description?: string
  uploadedFiles?: UploadedFile[]
}

interface ChapterConfig {
  id?: number
  chapterNumber: number
  title: string
  description: string
  isEnabled: boolean
  lecture?: MaterialConfigType
  slides?: MaterialConfigType
  video?: MaterialConfigType
  examples?: MaterialConfigType
  practice?: MaterialConfigType
  assignment?: MaterialConfigType
  createdAt?: string
  updatedAt?: string
}

interface Props {
  visible: boolean
  config?: ChapterConfig
}

const props = defineProps<Props>()
const emit = defineEmits(['close', 'save'])

const authStore = useAuthStore()
const loading = ref(false)
const error = ref('')
const minChapterNumber = ref(1)

interface ChapterConfigForm {
  chapterNumber: number
  title: string
  description: string
  isEnabled: boolean
  lectureConfig?: MaterialConfigType
  slidesConfig?: MaterialConfigType
  videoConfig?: MaterialConfigType
  exampleConfig?: MaterialConfigType
  practiceConfig?: MaterialConfigType
  assignmentConfig?: MaterialConfigType
  weightConfig: {
    lecture: number
    slides: number
    video: number
    example: number
    practice: number
    assignment: number
  }
}

// 表单数据
const formData = ref<ChapterConfigForm>({
  chapterNumber: 1,
  title: '',
  description: '',
  isEnabled: true,
  weightConfig: {
    lecture: 20,
    slides: 15,
    video: 20,
    example: 15,
    practice: 15,
    assignment: 15
  }
})

const isEdit = computed(() => !!props.config)
// const saving = ref(false) // 已移除，使用loading变量

// 计算总权重
const totalWeight = computed(() => {
  const weights = formData.value.weightConfig
  let total = 0
  
  if (formData.value.lectureConfig) total += weights.lecture || 0
  if (formData.value.slidesConfig) total += weights.slides || 0
  if (formData.value.videoConfig) total += weights.video || 0
  if (formData.value.exampleConfig) total += weights.example || 0
  if (formData.value.practiceConfig) total += weights.practice || 0
  if (formData.value.assignmentConfig) total += weights.assignment || 0
  
  return total
})

// 获取文件列表的辅助函数
const fetchFileList = async (chapterNumber: number, materialType: string) => {
  try {
    const response = await fetch(`http://localhost:806/api/file/files/${chapterNumber}/${materialType}`, {
      headers: {
        'Authorization': `Bearer ${authStore.token}`,
        'Content-Type': 'application/json'
      }
    })
    
    if (response.ok) {
      const result = await response.json()
      const files = result.data || []
      
      // 将绝对路径转换为相对路径
      return files.map((file: any) => {
        if (file.path) {
          // 提取public目录之后的相对路径
          const publicIndex = file.path.indexOf('\\public\\')
          if (publicIndex !== -1) {
            file.path = file.path.substring(publicIndex + 8) // 8 = '\\public\\'.length
          }
        }
        return file
      })
    }
  } catch (error) {
    console.error(`获取${materialType}文件列表失败:`, error)
  }
  return []
}

// 初始化表单
const initializeForm = async (config: ChapterConfig) => {
  console.log('Initializing form with config:', config)
  
  // 处理API返回的数据结构与前端期望的数据结构差异
  const apiConfig = config as any
  
  // 获取所有材料类型的文件列表
  const [docxFiles, pptxFiles, videoFiles, exampleFiles, practiceFiles, assignmentFiles] = await Promise.all([
    fetchFileList(config.chapterNumber, 'docx'),
    fetchFileList(config.chapterNumber, 'pptx'),
    fetchFileList(config.chapterNumber, 'video'),
    fetchFileList(config.chapterNumber, 'examples'),
    fetchFileList(config.chapterNumber, 'practice'),
    fetchFileList(config.chapterNumber, 'assignment')
  ])
  
  formData.value = {
    chapterNumber: config.chapterNumber,
    title: config.title || apiConfig.chapterTitle,
    description: config.description || apiConfig.chapterDescription || '',
    isEnabled: config.isEnabled !== undefined ? config.isEnabled : apiConfig.isActive,
    // 映射API返回的配置字段到前端期望的字段，确保保留uploadedFiles
    lectureConfig: {
      ...apiConfig.docxConfig,
      ...config.lecture,
      // 使用从API获取的最新文件列表
      uploadedFiles: docxFiles
    },
    slidesConfig: {
      ...apiConfig.pptxConfig,
      ...config.slides,
      // 使用从API获取的最新文件列表
      uploadedFiles: pptxFiles
    },
    videoConfig: {
      ...apiConfig.videosConfig,
      ...config.video,
      // 使用从API获取的最新文件列表
      uploadedFiles: videoFiles
    },
    exampleConfig: {
      ...apiConfig.examplesConfig,
      ...config.examples,
      // 使用从API获取的最新文件列表
      uploadedFiles: exampleFiles
    },
    practiceConfig: {
      ...apiConfig.practiceConfig,
      ...config.practice,
      // 使用从API获取的最新文件列表
      uploadedFiles: practiceFiles
    },
    assignmentConfig: {
      ...apiConfig.assignmentsConfig,
      ...config.assignment,
      // 使用从API获取的最新文件列表
      uploadedFiles: assignmentFiles
    },
    weightConfig: {
      lecture: (config.lecture?.weight || apiConfig.docxConfig?.weight) || (config.lecture || apiConfig.docxConfig ? 20 : 0),
      slides: (config.slides?.weight || apiConfig.pptxConfig?.weight) || (config.slides || apiConfig.pptxConfig ? 15 : 0),
      video: (config.video?.weight || apiConfig.videosConfig?.weight) || (config.video || apiConfig.videosConfig ? 20 : 0),
      example: (config.examples?.weight || apiConfig.examplesConfig?.weight) || (config.examples || apiConfig.examplesConfig ? 15 : 0),
      practice: (config.practice?.weight || apiConfig.practiceConfig?.weight) || (config.practice || apiConfig.practiceConfig ? 15 : 0),
      assignment: (config.assignment?.weight || apiConfig.assignmentsConfig?.weight) || (config.assignment || apiConfig.assignmentsConfig ? 15 : 0)
    }
  }
  
  console.log('Form data after initialization:', formData.value)
}

// 阻止键盘输入，只允许鼠标上下箭头操作
const preventKeyboardInput = (event) => {
  // 允许的键：上箭头、下箭头、Tab、Enter、Escape
  const allowedKeys = ['ArrowUp', 'ArrowDown', 'Tab', 'Enter', 'Escape']
  
  if (!allowedKeys.includes(event.key)) {
    event.preventDefault()
  }
}

// 获取最大章节号
const fetchMaxChapterNumber = async () => {
  try {
    const response = await fetch('http://localhost:806/api/chapter-config/max-chapter-number', {
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    if (response.ok) {
      const result = await response.json()
      return result.data.nextChapterNumber || 1
    }
  } catch (error) {
    console.error('获取最大章节号失败:', error)
  }
  return 1
}

// 重置表单
const resetForm = async () => {
  const nextChapterNumber = await fetchMaxChapterNumber()
  minChapterNumber.value = nextChapterNumber
  
  formData.value = {
    chapterNumber: nextChapterNumber,
    title: '',
    description: '',
    isEnabled: true,
    weightConfig: {
      lecture: 20,
      slides: 15,
      video: 20,
      example: 15,
      practice: 15,
      assignment: 15
    }
  }
}

// 监听配置变化
watch(() => props.config, async (newConfig) => {
  if (newConfig && props.visible) {
    await initializeForm(newConfig)
  }
}, { immediate: true })

// 组件挂载时获取最大章节号
onMounted(async () => {
  const nextChapterNumber = await fetchMaxChapterNumber()
  minChapterNumber.value = nextChapterNumber
  // 如果是新增模式，同时设置表单的章节号
  if (!props.config) {
    formData.value.chapterNumber = nextChapterNumber
  }
})

// 监听模态框显示状态
watch(() => props.visible, async (visible) => {
  if (visible) {
    error.value = ''
    if (props.config) {
      await initializeForm(props.config)
    } else {
      await resetForm()
    }
  }
})

// 监听各个配置项的权重变化，同步到底部权重配置
watch(() => formData.value.lectureConfig?.weight, (newWeight) => {
  if (newWeight !== undefined) {
    formData.value.weightConfig.lecture = newWeight
  }
})

watch(() => formData.value.slidesConfig?.weight, (newWeight) => {
  if (newWeight !== undefined) {
    formData.value.weightConfig.slides = newWeight
  }
})

watch(() => formData.value.videoConfig?.weight, (newWeight) => {
  if (newWeight !== undefined) {
    formData.value.weightConfig.video = newWeight
  }
})

watch(() => formData.value.exampleConfig?.weight, (newWeight) => {
  if (newWeight !== undefined) {
    formData.value.weightConfig.example = newWeight
  }
})

watch(() => formData.value.practiceConfig?.weight, (newWeight) => {
  if (newWeight !== undefined) {
    formData.value.weightConfig.practice = newWeight
  }
})

watch(() => formData.value.assignmentConfig?.weight, (newWeight) => {
  if (newWeight !== undefined) {
    formData.value.weightConfig.assignment = newWeight
  }
})

// 监听底部权重配置变化，同步到各个配置项
watch(() => formData.value.weightConfig.lecture, (newWeight) => {
  if (formData.value.lectureConfig && formData.value.lectureConfig.weight !== newWeight) {
    formData.value.lectureConfig.weight = newWeight
  }
})

// 处理各个MaterialConfig组件的更新事件
const handleLectureConfigUpdate = (config: MaterialConfigType | undefined) => {
  formData.value.lectureConfig = config
  if (config) {
    formData.value.weightConfig.lecture = config.weight || 20
  }
}

const handleSlidesConfigUpdate = (config: MaterialConfigType | undefined) => {
  formData.value.slidesConfig = config
  if (config) {
    formData.value.weightConfig.slides = config.weight || 15
  }
}

const handleVideoConfigUpdate = (config: MaterialConfigType | undefined) => {
  formData.value.videoConfig = config
  if (config) {
    formData.value.weightConfig.video = config.weight || 20
  }
}

const handleExampleConfigUpdate = (config: MaterialConfigType | undefined) => {
  formData.value.exampleConfig = config
  if (config) {
    formData.value.weightConfig.example = config.weight || 15
  }
}

const handlePracticeConfigUpdate = (config: MaterialConfigType | undefined) => {
  formData.value.practiceConfig = config
  if (config) {
    formData.value.weightConfig.practice = config.weight || 15
  }
}

const handleAssignmentConfigUpdate = (config: MaterialConfigType | undefined) => {
  formData.value.assignmentConfig = config
  if (config) {
    formData.value.weightConfig.assignment = config.weight || 15
  }
}

watch(() => formData.value.weightConfig.slides, (newWeight) => {
  if (formData.value.slidesConfig && formData.value.slidesConfig.weight !== newWeight) {
    formData.value.slidesConfig.weight = newWeight
  }
})

watch(() => formData.value.weightConfig.video, (newWeight) => {
  if (formData.value.videoConfig && formData.value.videoConfig.weight !== newWeight) {
    formData.value.videoConfig.weight = newWeight
  }
})

watch(() => formData.value.weightConfig.example, (newWeight) => {
  if (formData.value.exampleConfig && formData.value.exampleConfig.weight !== newWeight) {
    formData.value.exampleConfig.weight = newWeight
  }
})

watch(() => formData.value.weightConfig.practice, (newWeight) => {
  if (formData.value.practiceConfig && formData.value.practiceConfig.weight !== newWeight) {
    formData.value.practiceConfig.weight = newWeight
  }
})

watch(() => formData.value.weightConfig.assignment, (newWeight) => {
  if (formData.value.assignmentConfig && formData.value.assignmentConfig.weight !== newWeight) {
    formData.value.assignmentConfig.weight = newWeight
  }
})

// 表单验证
const validateForm = () => {
  if (!formData.value.title.trim()) {
    error.value = '请输入章节标题'
    return false
  }
  
  if (formData.value.chapterNumber < 1) {
    error.value = '章节号必须大于0'
    return false
  }
  
  // 检查是否至少配置了一种学习材料
  const hasAnyMaterial = formData.value.lectureConfig ||
                        formData.value.slidesConfig ||
                        formData.value.videoConfig ||
                        formData.value.exampleConfig ||
                        formData.value.practiceConfig ||
                        formData.value.assignmentConfig
  
  if (!hasAnyMaterial) {
    error.value = '请至少配置一种学习材料'
    return false
  }
  
  return true
}

// 关闭模态框
const closeModal = () => {
  emit('close')
}

// 提交表单
const handleSubmit = async () => {
  if (!validateForm()) {
    return
  }
  
  loading.value = true
  error.value = ''
  
  try {
    const token = authStore.token
    const url = isEdit.value 
      ? `http://localhost:806/api/chapter-config/${props.config?.id}`
      : 'http://localhost:806/api/chapter-config'
    
    const method = isEdit.value ? 'PUT' : 'POST'
    
    // 构建提交数据
    const submitData: any = {
      chapterNumber: formData.value.chapterNumber,
      chapterTitle: formData.value.title,
      chapterDescription: formData.value.description,
      isEnabled: formData.value.isEnabled
    }
    
    // 在编辑模式下，始终提交所有配置项，确保不丢失原有数据
    const apiConfig = isEdit.value ? props.config as any : null
    
    // 讲义配置
    if (formData.value.lectureConfig || (apiConfig && apiConfig.docxConfig)) {
      submitData.docxConfig = {
        weight: formData.value.lectureConfig?.weight || apiConfig?.docxConfig?.weight || 20,
        isRequired: formData.value.lectureConfig?.isRequired !== undefined ? formData.value.lectureConfig.isRequired : (apiConfig?.docxConfig?.isRequired || false),
        allowDownload: formData.value.lectureConfig?.allowDownload !== undefined ? formData.value.lectureConfig.allowDownload : (apiConfig?.docxConfig?.allowDownload || true),
        description: formData.value.lectureConfig?.description || apiConfig?.docxConfig?.description || '',
        uploadedFiles: formData.value.lectureConfig?.uploadedFiles || apiConfig?.docxConfig?.uploadedFiles || []
      }
    }
    
    // 课件配置
    if (formData.value.slidesConfig || (apiConfig && apiConfig.pptxConfig)) {
      submitData.pptxConfig = {
        weight: formData.value.slidesConfig?.weight || apiConfig?.pptxConfig?.weight || 15,
        isRequired: formData.value.slidesConfig?.isRequired !== undefined ? formData.value.slidesConfig.isRequired : (apiConfig?.pptxConfig?.isRequired || false),
        allowDownload: formData.value.slidesConfig?.allowDownload !== undefined ? formData.value.slidesConfig.allowDownload : (apiConfig?.pptxConfig?.allowDownload || true),
        description: formData.value.slidesConfig?.description || apiConfig?.pptxConfig?.description || '',
        uploadedFiles: formData.value.slidesConfig?.uploadedFiles || apiConfig?.pptxConfig?.uploadedFiles || []
      }
    }
    
    // 视频配置
    if (formData.value.videoConfig || (apiConfig && apiConfig.videosConfig)) {
      submitData.videosConfig = {
        weight: formData.value.videoConfig?.weight || apiConfig?.videosConfig?.weight || 20,
        isRequired: formData.value.videoConfig?.isRequired !== undefined ? formData.value.videoConfig.isRequired : (apiConfig?.videosConfig?.isRequired || false),
        allowDownload: formData.value.videoConfig?.allowDownload !== undefined ? formData.value.videoConfig.allowDownload : (apiConfig?.videosConfig?.allowDownload || true),
        duration: formData.value.videoConfig?.duration || apiConfig?.videosConfig?.duration || 0,
        description: formData.value.videoConfig?.description || apiConfig?.videosConfig?.description || '',
        uploadedFiles: formData.value.videoConfig?.uploadedFiles || apiConfig?.videosConfig?.uploadedFiles || []
      }
    }
    
    // 示例配置
    if (formData.value.exampleConfig || (apiConfig && apiConfig.examplesConfig)) {
      submitData.examplesConfig = {
        weight: formData.value.exampleConfig?.weight || apiConfig?.examplesConfig?.weight || 15,
        isRequired: formData.value.exampleConfig?.isRequired !== undefined ? formData.value.exampleConfig.isRequired : (apiConfig?.examplesConfig?.isRequired || false),
        allowDownload: formData.value.exampleConfig?.allowDownload !== undefined ? formData.value.exampleConfig.allowDownload : (apiConfig?.examplesConfig?.allowDownload || true),
        description: formData.value.exampleConfig?.description || apiConfig?.examplesConfig?.description || '',
        uploadedFiles: formData.value.exampleConfig?.uploadedFiles || apiConfig?.examplesConfig?.uploadedFiles || []
      }
    }
    
    // 练习配置
    if (formData.value.practiceConfig || (apiConfig && apiConfig.practiceConfig)) {
      submitData.practiceConfig = {
        weight: formData.value.practiceConfig?.weight || apiConfig?.practiceConfig?.weight || 15,
        isRequired: formData.value.practiceConfig?.isRequired !== undefined ? formData.value.practiceConfig.isRequired : (apiConfig?.practiceConfig?.isRequired || false),
        allowDownload: formData.value.practiceConfig?.allowDownload !== undefined ? formData.value.practiceConfig.allowDownload : (apiConfig?.practiceConfig?.allowDownload || true),
        description: formData.value.practiceConfig?.description || apiConfig?.practiceConfig?.description || '',
        uploadedFiles: formData.value.practiceConfig?.uploadedFiles || apiConfig?.practiceConfig?.uploadedFiles || []
      }
    }
    
    // 作业配置
    if (formData.value.assignmentConfig || (apiConfig && apiConfig.assignmentsConfig)) {
      submitData.assignmentsConfig = {
        weight: formData.value.assignmentConfig?.weight || apiConfig?.assignmentsConfig?.weight || 15,
        isRequired: formData.value.assignmentConfig?.isRequired !== undefined ? formData.value.assignmentConfig.isRequired : (apiConfig?.assignmentsConfig?.isRequired || false),
        allowDownload: formData.value.assignmentConfig?.allowDownload !== undefined ? formData.value.assignmentConfig.allowDownload : (apiConfig?.assignmentsConfig?.allowDownload || true),
        deadline: formData.value.assignmentConfig?.deadline || apiConfig?.assignmentsConfig?.deadline || '',
        description: formData.value.assignmentConfig?.description || apiConfig?.assignmentsConfig?.description || '',
        uploadedFiles: formData.value.assignmentConfig?.uploadedFiles || apiConfig?.assignmentsConfig?.uploadedFiles || []
      }
    }
    
    // 权重配置总是提交，因为它是必需的
    submitData.weightConfig = {
      lecture: formData.value.weightConfig.lecture,
      slides: formData.value.weightConfig.slides,
      video: formData.value.weightConfig.video,
      example: formData.value.weightConfig.example,
      practice: formData.value.weightConfig.practice,
      assignment: formData.value.weightConfig.assignment
    }
    
    console.log('Submit data:', submitData)

    const response = await fetch(url, {
      method,
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify(submitData)
    })

    if (!response.ok) {
      const errorData = await response.json()
      throw new Error(errorData.message || '保存失败')
    }

    const result = await response.json()
    emit('save', result)
    emit('close')
  } catch (err: any) {
    error.value = err.message || '保存失败，请重试'
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
/* 组件特定样式 */
</style>